package com.example.spider;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.Timeout;

import java.io.IOException;

public class demo {
    public static void main(String[] args) throws Exception {
        //模拟浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建请求
        HttpGet httpGet = new HttpGet("https://nipic.com/");
        //配置请求参数
        RequestConfig config = RequestConfig.custom().setConnectTimeout(Timeout.ofSeconds(1))//设置连接最大超时时间
                .setConnectionRequestTimeout(Timeout.ofSeconds(1))//获取连接的最大时间
                .setResponseTimeout(Timeout.ofSeconds(10))//数据最大传输时间
                .build();
        //设置请求参数
        httpGet.setConfig(config);
        //发送请求，获得结果
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //解析数据
        if (response.getCode() == 200){
            HttpEntity httpEntity = response.getEntity();
            String res = EntityUtils.toString(httpEntity, "utf8");
            System.out.println(res);
        }else {
            System.err.println("解析失败！");
        }
    }
}
